package it.slkfarm.android;


import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;



import it.slkfarm.android.R;
import it.slkfarm.gps.GpsTracker;
import it.slkfarm.helpers.DialogBuilder;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomButton;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

@SuppressLint("NewApi")
public class FarmMap extends MapActivity implements OnClickListener, OnCheckedChangeListener
{
	/**
	 * @uml.property  name="mapView"
	 * @uml.associationEnd  
	 */
	private MapView mapView;
	/**
	 * @uml.property  name="mapController"
	 * @uml.associationEnd  
	 */
	private MapController mapController;
	/**
	 * @uml.property  name="overlay"
	 * @uml.associationEnd  inverse="this$0:it.slkfarm.android.FarmMap$MyOverlay"
	 */
	private MyOverlay overlay;
	/**
	 * @uml.property  name="locationManager"
	 * @uml.associationEnd  readOnly="true"
	 */
	private LocationManager locationManager;
	/**
	 * @uml.property  name="location"
	 * @uml.associationEnd  
	 */
	private Location location;
	/**
	 * @uml.property  name="point"
	 * @uml.associationEnd  
	 */
	private GeoPoint point;
	/**
	 * @uml.property  name="isSriLanka"
	 */
	private boolean isSriLanka = true;
	/**
	 * @uml.property  name="criteria"
	 * @uml.associationEnd  readOnly="true"
	 */
	private Criteria criteria;
	/**
	 * @uml.property  name="provider"
	 */
	private String provider;
	/**
	 * @uml.property  name="tag"
	 */
	private String tag;
	/**
	 * @uml.property  name="latitude"
	 */
	private double latitude;
	/**
	 * @uml.property  name="longitude"
	 */
	private double longitude;
	/**
	 * @uml.property  name="altitude"
	 */
	private double altitude;
	/**
	 * @uml.property  name="minus"
	 * @uml.associationEnd  readOnly="true"
	 */
	private ZoomButton minus;
	/**
	 * @uml.property  name="plus"
	 * @uml.associationEnd  readOnly="true"
	 */
	private ZoomButton plus;
	/**
	 * @uml.property  name="confirm"
	 * @uml.associationEnd  
	 */
	private Button confirm;
	/**
	 * @uml.property  name="lang"
	 */
	private int lang;
	/**
	 * @uml.property  name="tv"
	 * @uml.associationEnd  
	 */
	private TextView tv;
	/**
	 * @uml.property  name="group"
	 * @uml.associationEnd  
	 */
	private RadioGroup group;
	/**
	 * @uml.property  name="yes"
	 * @uml.associationEnd  
	 */
	private RadioButton yes;
	/**
	 * @uml.property  name="no"
	 * @uml.associationEnd  
	 */
	private RadioButton no;
	/**
	 * @uml.property  name="tf"
	 * @uml.associationEnd  
	 */
	private Typeface tf;
	/**
	 * @uml.property  name="farmName"
	 * @uml.associationEnd  
	 */
	private EditText farmName;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="toast"
	 * @uml.associationEnd  
	 */
	private Toast toast;
	/**
	 * @uml.property  name="gps"
	 * @uml.associationEnd  
	 */
	private GpsTracker gps;
	/**
	 * @uml.property  name="dialog"
	 * @uml.associationEnd  
	 */
	private Dialog dialog;

	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		lang = getIntent().getIntExtra(getPackageName() + ".lang", 1);
		Resources res = this.getResources();
	    DisplayMetrics dm = res.getDisplayMetrics();
	    android.content.res.Configuration conf = res.getConfiguration();
		if (lang == Base.EN_LANG)
		{
			conf.locale = Locale.getDefault();
			tf = Typeface.createFromAsset(getAssets(),"fonts/KMKDSP__.ttf");
		}
		
		else 
		{	
			conf.locale = new Locale(Base.LOCALE_SRILANKA);
			 tf = null;
		}
		res.updateConfiguration(conf, dm);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.custom_dialog_farm);
		getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		mapView = (MapView) findViewById(R.id.farmMap);
		mapController = mapView.getController();
		mapView.setClickable(false);
		mapView.setBuiltInZoomControls(true);
		mapController.setZoom(8);
		gps = new GpsTracker(this);
		
		
		confirm = (Button) findViewById(R.id.btnInsertFarmConfirm);
		confirm.setTypeface(tf);
		confirm.setOnClickListener(this);
		
		tv = (TextView) findViewById(R.id.tvInsertFarmTitle);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvInsertFarmQuestion);
		tv.setTypeface(tf);
		
		group = (RadioGroup) findViewById(R.id.radioGroupFarm);
		yes = (RadioButton) findViewById(R.id.yes);
		no = (RadioButton) findViewById(R.id.no);
		
		yes.setTypeface(tf);
		no.setTypeface(tf);
		
		group.setOnCheckedChangeListener(this);
		
		farmName = (EditText) findViewById(R.id.editFarmName);
		farmName.setTypeface(tf);
		
		farmName.addTextChangedListener(new TextWatcher() 
		{
			
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		location = gps.getLocation();
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		Double geoLat = location.getLatitude()*1E6;
		Double geoLng = location.getLongitude()*1E6;
		Log.i("lat", String.valueOf(geoLat));
		Log.i("lng", String.valueOf(geoLng));
		point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
		mapController.animateTo(point);
		overlay = new MyOverlay();
		List<Overlay> listOverlays = mapView.getOverlays();
		listOverlays.clear();
		listOverlays.add(overlay);
		mapView.invalidate();
		builder = new DialogBuilder(this, lang);
	}
	
	
	
	@Override
	public void onPause() 
	{
		super.onPause();
		gps.stopUsingGps();
	}

	@Override
	protected void onResume() 
	{
		super.onResume();
		location = gps.getLocation();
	}

	public static double getRound(double x, int digits)
	{
		double powerOfTen = Math.pow(10, digits);
		return (Math.round(x * powerOfTen) / powerOfTen);
	}

	@Override
	protected boolean isRouteDisplayed() 
	{	
		return false;
	}
	
	public class MyOverlay extends com.google.android.maps.Overlay
	{
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
		{
			super.draw(canvas, mapView, shadow);
			Point screenPoint = new Point();
			mapView.getProjection().toPixels(point, screenPoint);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.point);
			canvas.drawBitmap(bmp, screenPoint.x, screenPoint.y-36,null);
			return true;
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView)
		{
			if (event.getAction() == 1)
			{
				point = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY());
				mapController.animateTo(point);
				Geocoder geoCoder = new Geocoder(FarmMap.this, Locale.getDefault());
				List<Address> list = new ArrayList<Address>();
				latitude = point.getLatitudeE6()/1E6;
				longitude = point.getLongitudeE6()/1E6;
				altitude = getElevationFromGoogleMaps(longitude, latitude);
				try 
				{
					list = geoCoder.getFromLocation(point.getLatitudeE6()/1E6, point.getLongitudeE6()/1E6, 1);	
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				}
				if (list.size()>0)
				{
					isSriLanka = true;
					Address app = list.get(0);
					if (!app.getCountryName().equals("Sri Lanka") || altitude < 0.0)
						isSriLanka = false;				
				}	
				else
					isSriLanka = false;
				return true;
			}
			else
				return false;		
		}
	}

	
	public void onClick(View v) 
	{		
		if (v.getId() == R.id.btnInsertFarmConfirm)
		{
			if (!isSriLanka)
			{
				dialog = builder.createDialog(R.string.error, R.string.error_location, null, null);
				dialog.show();
			}
			else
			{
				String name = farmName.getText().toString();
				if (name.equalsIgnoreCase(""))
				{
					toast = builder.createToast(R.string.error_farm, null, this);
					toast.show();
				}
				else
				{

					Intent intent = new Intent();
					String pk = getPackageName();
					intent.putExtra(pk + ".latitude", latitude);
					intent.putExtra(pk + ".longitude", longitude);
					intent.putExtra(pk + ".name", name);
					setResult(RESULT_OK,intent);
					finish();
				}			
			}
		}
	}
	
	private double getElevationFromGoogleMaps(double longitude, double latitude) 
	{
        double result = Double.NaN;
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String url = "http://maps.googleapis.com/maps/api/elevation/"
                + "xml?locations=" + String.valueOf(latitude)
                + "," + String.valueOf(longitude)
                + "&sensor=true";
        HttpGet httpGet = new HttpGet(url);
        try 
        {
            HttpResponse response = httpClient.execute(httpGet, localContext);
            HttpEntity entity = response.getEntity();
            if (entity != null) 
            {
                InputStream instream = entity.getContent();
                int r = -1;
                StringBuffer respStr = new StringBuffer();
                while ((r = instream.read()) != -1)
                    respStr.append((char) r);
                String tagOpen = "<elevation>";
                String tagClose = "</elevation>";
                if (respStr.indexOf(tagOpen) != -1) 
                {
                    int start = respStr.indexOf(tagOpen) + tagOpen.length();
                    int end = respStr.indexOf(tagClose);
                    String value = respStr.substring(start, end);
                    result = Double.parseDouble(value);
                }
                instream.close();
            }
        } 
        catch (ClientProtocolException e) {} 
        catch (IOException e) {}
        result = new BigDecimal(result).setScale(2 , BigDecimal.ROUND_UP).doubleValue();
        return result;
    }

	public void onCheckedChanged(RadioGroup arg0, int v) 
	{
		
		if (v == yes.getId())
		{
			mapView.setClickable(false);
			toast = builder.createToast(R.string.map_disable, null, this);
			toast.show();
		}
		else
		{
			mapView.setClickable(true);
			toast = builder.createToast(R.string.map_enabled, null, this);
			toast.show();
		}
	}
}
